package net.learn2develop.GPS;
 
import java.util.List;

import net.learn2develop.DB.DatabaseHelper;
import net.learn2develop.view.Markers;
import net.learn2develop.view.MyItemizedOverlay;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import android.graphics.drawable.Drawable;

import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;
 
public class GPS extends MapActivity {    
    		
		private MapView mapView; 
		private MapController mc;
		private GeoPoint p;
		private LocationManager lm;
		private LocationListener locationListener;
		private Spinner spinner;
		private Drawable[] markers;
		private List<Overlay> mapOverlays;
		private ProgressDialog pd;
		private String attributes [] = {"nameplace" , "latitud", "longitud", "address", "phone", "url", "email", "icon", "photo", "promotion", "_id"};
		private String[] infoPlace;
		private String conex;
		private SQLiteDatabase db;
		Bundle savedInstanceState;

	/** Called when the activity is first created. */ 
	@Override
    public void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
       
       	//lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);    
       	//locationListener = new MyLocationListener24();
       	//lm.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,locationListener);
        
	    spinner = (Spinner) this.findViewById(R.id.spinner1);
	    mapView = (MapView) findViewById(R.id.mapView);
	    mc = mapView.getController();
	    
	    ArrayAdapter<CharSequence> adapter = new ArrayAdapter<CharSequence>(this, android.R.layout.simple_spinner_item); 
	    loadMarkers();
	    
        try {
        	DatabaseHelper dbh = new DatabaseHelper(this);
        	db = dbh.getWritableDatabase();
        	//Actualiza la tabla SIEMPRE, via NETWORK
        	//dbh.onUpgrade(db, 1, 2);
        	Cursor cursor = db.rawQuery("SELECT categoryname FROM category",new String[]{});
        	        	
        	if (cursor.moveToFirst()) {
		 	    do {
		 	    	adapter.add(cursor.getString(0));
		 	       } while (cursor.moveToNext());
		 	}
		 	
        	if (cursor != null && !cursor.isClosed()) {
		 	         cursor.close();
		 	}
        	
        	adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        	spinner.setAdapter(adapter);
	        spinner.setOnItemSelectedListener(selectListener);	
        	
        } catch (Exception e) {
			System.out.println("XML Pasing Excpetion = " + e);
		}

	}
	
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		switch (keyCode) {
		case KeyEvent.KEYCODE_I:
			mc.setZoom((mapView.getZoomLevel() + 1));
			break;
		case KeyEvent.KEYCODE_O:
			mc.setZoom(mapView.getZoomLevel() - 1);
			break;
		}
		return super.onKeyDown(keyCode, event);
	}

     public void gotoSelected() {

          int pos = spinner.getSelectedItemPosition()+1;
          
          mapOverlays = mapView.getOverlays();
          mapOverlays.clear();
          
          Cursor cursor = db.rawQuery("SELECT nameplace, latitud, longitud, address, phone, url, email, icon, photo, promotion, _id " +
          		"FROM places WHERE categoryId LIKE ?",new String[]{""+Integer.valueOf(pos)});
      	  
          if (cursor.moveToFirst()) {
		 	    do {
		 	    	infoPlace = new String[11];
		 	    	for (int item = 0; item < attributes.length; item++){
			      		//ubico info en cada variable
					    infoPlace[item] = cursor.getString(cursor.getColumnIndex(attributes[item]));	  
		        	}
		 	    	
		 	    	double lat = Double.parseDouble(infoPlace[1]);
			        double lon = Double.parseDouble(infoPlace[2]);
			        
		 	    	p = new GeoPoint((int) (lat * 1E6), (int) (lon * 1E6));
			        
			        mc.animateTo(p);
			        mc.setZoom(15);
			        
			        addMarker(mapOverlays,0,infoPlace);
		 	    	
		 	       } while (cursor.moveToNext());
		 }
		 	
      	 if (cursor != null && !cursor.isClosed()) {
		 	         cursor.close();
		 }
          	      
	    //At first set my location
//          DialogInterface.OnCancelListener dialogCancel = new DialogInterface.OnCancelListener() {
//              public void onCancel(DialogInterface dialog) { 
//              }
//          };
//  		
//  		  pd = ProgressDialog.show(this, this.getResources().getString(R.string.search), 
//  				this.getResources().getString(R.string.search_signal_gps), true, true, dialogCancel);
//  		  lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
//  		
//  	      if (lm.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
//  			conex = "GPS";
//  			locationListener = new MyLocationListener();
//  			lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
//
//  		  }else {
//  			conex = "NETWORK";
//  			locationListener = new MyLocationListener();
//  			lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
//  		  }
          //At first set my location
          
     }
     
     /**
 	 * Add a marker and a balloon for each place.
 	 * 
 	 * @param mapOverlays - list of overlays (including this) on the MapView.
 	 * @param idMarker - marker chosen.
 	 * @param infoPlace - contains info about place.
 	 */ 
     public void addMarker(List<Overlay> mapOverlays, int idMarker, String[] infoPlace){
		
    	//Drawable image = LoadImageFromWebOperations(infoPlace[5]);
    	//Drawable image = LoadImageFromWebOperations("http://www.fastfoodfactory.com/wp-content/uploads/2009/05/mc-donalds-logo.png");
    	String image = "<img src='"+infoPlace[8]+"'>"; 
       	MyItemizedOverlay itemizedOverlay = new MyItemizedOverlay(markers[idMarker], mapView, image, Integer.valueOf(infoPlace[10]));
		String info = " ";
    	for (int r = 3;r<7;r++){
			info = info+infoPlace[r]+" ";
		} 	
		OverlayItem overlayItem = new OverlayItem(p, infoPlace[0],info);
		itemizedOverlay.addOverlay(overlayItem);
		//marker.addOverlay(overlayItem);
		//mapOverlays.add(marker);
		mapOverlays.add(itemizedOverlay);
		mapView.invalidate();
    }
    
    public void addMyLocationMarker(List<Overlay> mapOverlays, int i){
		
		Markers marker = new Markers(markers[i],this);
		OverlayItem overlayItem = new OverlayItem(p, "Mi Ubicacion", "Mi Ubicacion");
		marker.addOverlay(overlayItem);
		mapOverlays.add(marker);
		mapView.invalidate();
    }
    
    public void loadMarkers(){
    	
    	markers = new Drawable[11];
    	markers[0] = this.getResources().getDrawable(R.drawable.a);
    	markers[1] = this.getResources().getDrawable(R.drawable.b);
    	markers[2] = this.getResources().getDrawable(R.drawable.c);
    	markers[3] = this.getResources().getDrawable(R.drawable.d);
    	markers[4] = this.getResources().getDrawable(R.drawable.e);
    	markers[5] = this.getResources().getDrawable(R.drawable.f);
    	markers[6] = this.getResources().getDrawable(R.drawable.g);
    	markers[7] = this.getResources().getDrawable(R.drawable.h);
    	markers[8] = this.getResources().getDrawable(R.drawable.i);
    	markers[9] = this.getResources().getDrawable(R.drawable.j);
    	markers[10] = this.getResources().getDrawable(R.drawable.blue);
    }
        
    public boolean onCreateOptionsMenu(Menu menu){

    	menu.add(0,1,0,"My Location").setIcon(android.R.drawable.ic_menu_mylocation);
    	menu.add(0,2,0,"Ver Listado").setIcon(android.R.drawable.ic_menu_myplaces);
    	menu.add(0,3,0,"Search").setIcon(android.R.drawable.ic_menu_search);
    	menu.add(0,4,0,"Favorites").setIcon(android.R.drawable.star_big_off);
    	menu.add(0,5,0,"Filter").setIcon(android.R.drawable.ic_menu_info_details);
    	return true;

   }
    
    public boolean onOptionsItemSelected (MenuItem item){

    	switch (item.getItemId()){
    	case 1:
    		DialogInterface.OnCancelListener dialogCancel = new DialogInterface.OnCancelListener() {
                public void onCancel(DialogInterface dialog) { 
                }
            };
    		
    		pd = ProgressDialog.show(this, this.getResources().getString(R.string.search), 
    				this.getResources().getString(R.string.search_signal_gps), true, true, dialogCancel);
    		lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
    		
    		if (lm.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
    			conex = "GPS";
    			locationListener = new MyLocationListener();
    			lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);

    		} else {
    			conex = "NETWORK";
    			locationListener = new MyLocationListener();
    			lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
    		}
    	return true;
       	
    	case 2:
    		//finish();
    		Intent intent = new Intent(getBaseContext(), PlacesList.class);
    		intent.putExtra("CATEGORY_ID", spinner.getSelectedItemPosition()+1);
    		startActivity(intent);
        return true;
        
    	case 3:
        	startActivity(new Intent(getBaseContext(), Search.class));

        return true;
        
    	case 4:
 
        	startActivity(new Intent(getBaseContext(), FavoritesList.class));
    		
    	return true;
    	
    	case 5:
    		 
        	startActivity(new Intent(getBaseContext(), Filter.class));
    		
    	return true;
        
    	}
    	return false;
    }
    
    

    private OnItemSelectedListener selectListener = new OnItemSelectedListener() {
  		public void onItemSelected(AdapterView<?> parent, View v, int position, long id) {
  			gotoSelected();
  		}
  		public void onNothingSelected(AdapterView<?> arg0) {}
  	};
 
    @Override
    protected boolean isRouteDisplayed() {
        // TODO Auto-generated method stub
        return false;
    }
    
    private class MyLocationListener implements LocationListener {
    	@Override
        public void onLocationChanged(Location loc) {
    			if (loc != null) {                
            		pd.dismiss();
            		Toast.makeText(getBaseContext(),getResources().getString(R.string.gps_signal_found)+" con "+conex,Toast.LENGTH_SHORT).show();
            		p = new GeoPoint((int) (loc.getLatitude() * 1E6),(int) (loc.getLongitude() * 1E6));
            		mc.animateTo(p);
            		mc.setZoom(17);
            		mapOverlays = mapView.getOverlays();
                    mapOverlays.clear();
            		addMyLocationMarker(mapOverlays, 10);
        			lm.removeUpdates(locationListener);
            	}else {
                	Toast.makeText(getBaseContext(), 
                	getResources().getString(R.string.gps_signal_found),Toast.LENGTH_LONG).show();

                }
        }
        
        @Override
        public void onProviderDisabled(String provider) {
            // TODO Auto-generated method stub
        }

        @Override
        public void onProviderEnabled(String provider) {
            // TODO Auto-generated method stub
        }

        @Override
        public void onStatusChanged(String provider, int status, 
            Bundle extras) {
            // TODO Auto-generated method stub
        }
        
   }

}

